// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Popconfirm, Upload, message, Button, Modal, Row, Col, Input, Divider } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
import { reqInform } from 'utils/notification'
// 当前组件样式
import styles from './giftListStyle.less'
import Uploader from '../../../../widget/Upload'
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'
import $ from 'jquery'
import Cookie from 'js-cookie'
import { download } from 'utils/util'
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'

const FormItem = Form.Item
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
}
const formItemLayout2 = {
  labelCol: { span: 3 },
  wrapperCol: { span: 16 },
}
const giftListView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model

  // modelObj.xxx获取model中状态机的值
  let { areaList, modalObj, checkBtn, codeQuery, codeList } = modelObj
  console.log(modalObj, codeQuery, codeList)
  // 点击处理事件
  // const clickHandler = (e) => {
  //   // 分发到model文件中effects的xxx方法
  //   dispatch({
  //     type: `${namespace}/xxx`,
  //     payload: {}
  //   })
  // }

  //下载excel
  // function downFile(url, fileName = 'report.xls') {
  //   var link = document.createElement('a')
  //   let evt = document.createEvent('MouseEvents')
  //   evt.initEvent('click', true, true)
  //   link.href = url
  //   link.dispatchEvent(evt)

  // }

  //礼品核销
  function checkGift() {
    modalObj.visible = !modalObj.visible
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { modalObj }
    })
  }

  function updateModal() {
    modalObj.visible = !modalObj.visible
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { modalObj,codeQuery:{},checkBtn:true,codeList:{} }
    })
  }

  //验证按钮
  function checkCode(e) {
    let { userGiftId } = codeQuery
    dispatch({
      type: `${namespace}/doCheckCode`,
      payload: { userGiftId }
    })
    // dispatch({
    //   type: `${namespace}/updateStore`,
    //   payload: { checkBtn, codeQuery }
    // })
    resetFields(['userGiftId'])
    resetFields(['remark'])

  }

  function detailSkip(type, giftId) {
    hashHistory.push({
      pathname: '/home/infoAdmin/giftAdd',
      query: { actionType: type, giftId }
    })
  }

  function inputChange(value, type) {

    codeQuery[type] = value
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { codeQuery }
    })
  }
  //
  function okVerific() {
    dispatch({
      type: `${namespace}/doOkVerific`,
    })

  }

  function addOrEditSkip(type, item) {
    // console.log(MODULE_TO_ROUTES.namespace);
    // console.log(id)
    let giftAdd = `/home/infoAdmin/giftAdd`
    let giftDetail = `/home/infoAdmin/giftDetail`
    let routerLink = type == 'edit' ? giftAdd : giftDetail;
    let editQuery = item.giftId
    let detailQuery = item
    let query = type == 'edit' ? editQuery : detailQuery
    if (type == 'edit') {
      hashHistory.push({
        pathname: routerLink,
        query: { actionType: type, giftId: editQuery }
      })
    } else {
      hashHistory.push({
        pathname: routerLink,
        query: { actionType: type, ...detailQuery }
      })
    }

  }
  // 分页表格属性配置
  let pageProps = {
    // ---------- 界面部分 ----------
    'ui': {
      // 页面接口地址
      'api_url': 'admin/gift/list',
      // "api_url": "admin/housetype/list",
      // 接口方式
      'method': 'POST',
      'app': 'isales-mgmt-application',
      // 接口参数
      'params': '',
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      'mockData': null,
      // 查询栏
      'search_bar': {
        'fields': [
          {
            en_name: 'province',
            zh_name: '省市',
            elem_type: 'Cascader',
            elem_valid_type: 'string',
            cmpt_items: areaList,
            //关联的更改的搜索字段 
            related_key: 'projectId',
            //请求地址
            related_req_url: 'admin/estate/adminList',
            //默认请求
            related_req_param: {
              pageNo: 1,
              pageSize: 1000
            },
            split_keys: ['province', 'city'],
          },
          {
            en_name: 'projectId',
            zh_name: '项目名称',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: []
          },
          {
            en_name: 'title',
            zh_name: '礼品名称',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
        ],
        searchHandler: (p) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click', p)
        },
        resetHandler: (p) => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click', p)
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      'table': {
        'status_params': 'status=0',
        'status_text': '全部',
        'scroll': { x: 2000 },
        'action_props': { width: 200 },
        // 表头字段列表"
        'fields': [
          {
            'en_name': 'title',
            'zh_name': '礼品名称',
            width: 200
          },
          {
            'en_name': 'projectName',
            'zh_name': '所属项目',
            width: 200
          },
          {
            'en_name': 'city',
            'zh_name': '所属城市',
            width: 200,
            render: (a, item, index, d, e, f) => {
              // console.log(a, item, index, d, e, f)
              return <span>{item.provinceName}-{item.cityName}</span>
            }
          },
          {
            'en_name': 'totalStock',
            'zh_name': '库存量',
            // width: 274,
          },
          {
            'en_name': 'shelfStock',
            'zh_name': '上架库存',
            width: 80,
          },
          {
            'en_name': 'applyCount',
            'zh_name': '已申领数量',
            width: 80,
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  {item.applyCount ? item.applyCount : '0'}
                </span>
              )
            }
          },
          {
            'en_name': 'shelfStatus',
            'zh_name': '状态',
            width: 80,
            render: (text, record) => {
              return <div>
                {{ true: '已上架', false: '已下架' }[text] || ''}
              </div>
            }
          },
          {
            'en_name': 'limitCount',
            'zh_name': '限领数量',
            width: 100,
          },
          {
            'en_name': 'remark',
            'zh_name': '领取规则',
            width: 100,
          },
          {
            'en_name': 'lqqx',
            'zh_name': '领取期限',
            width: 240,
            render: (text, item) => {
              return <div>{`${item.startOnlineTime.split(' ')[0] || ''}${item.endOnlineTime && ' ~ ' || ''}${item.endOnlineTime.split(' ')[0] || ''}`}</div>
            }
          },
          {
            'en_name': 'createTime',
            'zh_name': '创建时间',
            width: 200,
          },
          {
            'en_name': 'updateTime',
            'zh_name': '更新时间',
            width: 200,
          },
          {
            'en_name': 'updatePerson',
            'zh_name': '更新人',
            width: 80,
          },
          {
            en_name: "edit",
            zh_name: "操作",
            width: 210,
            fixed: 'right',
            render: (a, item, index, d, e, f) => {
              return (
                <span>
                  {/* <a onClick={() => addOrEditSkip('check', item)}>查看记录详细<span className="ant-divider" style={{ display: 'inline-block' }} /></a>
                  <a onClick={() => addOrEditSkip('edit', item)}>编辑<span className="ant-divider" /></a>
                  <Popconfirm Collapse title='确定要删除该礼品码吗？' okText='确定' cancelText='取消'
                    onConfirm={() => {
                      dispatch({
                        type: `${namespace}/deleteGift`,
                        payload: { giftId: item.giftId }
                      })
                    }}>
                    <Link>删除</Link>
                  </Popconfirm> */}
                  <FlagBtn node={<a onClick={() => addOrEditSkip('check', item)}>查看记录详细<span className="ant-divider" style={{ display: 'inline-block' }} /></a>} btnId={'20404'}> </FlagBtn>
                  <FlagBtn node={<a onClick={() => addOrEditSkip('edit', item)}>编辑<span className="ant-divider" /></a>} btnId={'20403'}> </FlagBtn>
                  {/* <FlagBtn node={<Popconfirm Collapse title='确定要删除该礼品码吗？' okText='确定' cancelText='取消'
                    onConfirm={() => {
                      dispatch({
                        type: `${namespace}/deleteGift`,
                        payload: { giftId: item.giftId }
                      })
                    }}>
                    <Link>删除</Link>
                  </Popconfirm>} btnId={'20305'}>
                  </FlagBtn> */}
                 
                </span>
              )
            },
          }

        ],

        // 'actions': [
        //   {
        //     func_name: 'bussinessDetail',
        //     label: '业务详情',
        //     render: (record) => {
        //       let linkQuery = {
        //         giftId:record.giftId,
        //         title:record.title,
        //         totalStock:record.totalStock,
        //         shelfStock:record.shelfStock,
        //         receiveCount:record.receiveCount,
        //       }
        //       return (
        //         <div>
        //           <FlagBtn node={<Link to='home/giftAdmin/giftDetail' query={{...linkQuery}}>查看记录详细<span className="ant-divider" style={{ display: 'inline-block' }} /></Link>} btnId={'20302'}> </FlagBtn>
        //           <FlagBtn node={<Link to='home/giftAdmin/giftAdd' query={{ giftId: record.giftId,actionType:'edit'}}>编辑<span className="ant-divider" style={{ display: 'inline-block' }} /></Link>} btnId={'20303'}> </FlagBtn>
        //           <FlagBtn node={<Popconfirm Collapse title='确定要删除该优惠券吗？' okText='确定' cancelText='取消'
        //             onConfirm={() => {
        //               dispatch({
        //                 type: `${namespace}/deleteGift`,
        //                 payload: {  giftId: record.giftId }
        //               })
        //             }}>
        //             <Link>删除</Link>
        //           </Popconfirm>} btnId={'20305'}> </FlagBtn>
        //         </div>
        //       )
        //     }
        //   }
        // ],
        action_props: {
          fixed: "right",
          width: 210
        }
      },
      // 操作栏
      action_bar: [
        {
          'func_name': 'add',
          'label': '新增礼品',
          btnId: '20401',
          'type': 'primary',
          'onClick': (e) => {
            detailSkip("add")
          }
        },
        {
          'func_name': 'add',
          'label': '礼品核销',
          btnId: '20402',
          'type': 'primary',
          'onClick': (e) => {
            checkGift(e)
          }
        }
      ],
    },
  }

  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { biz }
      })
    }
  }

  return (
    <div className={cx('pageLayout')}>
      <Modal
        title={'提取码领取'}
        width='460px'
        // className="pubBiz_CommonModel"
        visible={modalObj.visible}
        // visible='false'
        onCancel={() => { updateModal() }}
        footer={null}
      >
        <div className={styles.detailContainer}>
          <Form>
            <Row>
              <Col span={18}>
                <FormItem
                  {...formItemLayout}
                  label="提取码">
                  {getFieldDecorator('userGiftId', {
                    initialValue: codeQuery.userGiftId ? codeQuery.userGiftId : '',
                    rules: [
                      { required: false, whitespace: true, message: '请输入8位数提取码' }
                    ],
                  })(<Input
                    // disabled={checkBtn === false}
                    placeholder={'请输入8位数提取码'}
                    onChange={(e) => { inputChange(e.target.value, 'userGiftId') }}
                  />)}
                </FormItem>
              </Col>
              <Col>
                {checkBtn ? <Button style={{ marginTop: '4px' }} type="primary" onClick={(e) => { checkCode(e) }}>验证</Button> : <Button style={{ marginTop: '4px' }} type="primary" onClick={(e) => { okVerific(e) }}>确认核销</Button>}

              </Col>
            </Row>
            {!checkBtn &&
              <Row>
                <FormItem
                  {...formItemLayout2}
                  label="备注">
                  {getFieldDecorator('remark', {
                    initialValue: codeQuery.remark ? codeQuery.remark : '',
                    rules: [
                      { required: false, whitespace: true, message: '请输入备注信息' }
                    ],
                  })(<Input
                    // disabled={(pageType == "detail") ||includes(detailInfo.published,['2'])? true : false}
                    placeholder={'请输入备注信息'}
                    onChange={(e) => { inputChange(e.target.value, 'remark') }}
                  />)}
                </FormItem>
              </Row>
            }

          </Form>
          {!checkBtn &&
            <Row>
              <Divider />
              <table className={styles.tableBox}>
                <tbody>
                  <tr>
                    <th>礼品名称</th>
                    <th>数量</th>
                    <th>兑换条件</th>
                  </tr>
                  <tr>
                    <td>{codeList.title}</td>
                    <td>{codeList.applyCount}</td>
                    <td>{codeList.remark}</td>
                  </tr>
                </tbody>
              </table>
            </Row>
          }

        </div>
      </Modal>
      <ListPage pageProps={pageProps} />
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(giftListView))
